﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using StockLib.Data;

namespace StockLib.Quote
{
    public partial class StockReceiver
    {

        /// <summary>
        /// 补充除权数据
        /// </summary>
        /// <param name="data">接收数据结构</param>
        private void ReceiveFilePower(ref ReceiveData data)
        {
            List<XdrData> kdata = new List<XdrData>();
            Stock stock = new Stock();
            ReceivePowerFilePack pack;
            ReceiveFileHead head;

            try
            {
                int packSize = Marshal.SizeOf(typeof(ReceivePowerFilePack));
                for (int i = 0; i < data.m_nPacketNum; i++)
                {
                    IntPtr pointer = new IntPtr((int)data.m_pData + i * packSize);
                    head = (ReceiveFileHead)Marshal.PtrToStructure(pointer, typeof(ReceiveFileHead));
                    pack = (ReceivePowerFilePack)Marshal.PtrToStructure(pointer, typeof(ReceivePowerFilePack));
                    if (head.m_dwHeadTag == EKE_HEAD_TAG)
                    {
                        if (kdata.Count > 0)
                        {
                            //保存到文件
                            StockData.Instance.SaveXdrData(stock, kdata);
                            kdata.Clear();
                        }

                        // 保存股票信息
                        stock.Market = ConvertMarketToInternal(head.m_wMarket);
                        stock.Code = head.m_szLabel;
                    }
                    else
                    {
                        // 转换数据包
                        XdrData k = new XdrData();
                        ConvertPowerFilePackToInternal(ref pack, k);
                        kdata.Add(k);
                    }
                }
                if (kdata.Count > 0)
                {
                    //保存到文件
                    StockData.Instance.SaveXdrData(stock, kdata);
                    kdata.Clear();
                }

                // 通知除权数据接收
                OnDataChanged(this, new ReceiverDataEventArgs(DataType.XDR));
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("文件操作出错 股票代码:{0} 异常信息:{1}", stock.Code, ex.ToString()));
                throw ex;
            }
        }

        private void ConvertPowerFilePackToInternal(ref ReceivePowerFilePack powerPack, XdrData xdrData)
        {
            xdrData.Time = powerPack.m_time;
            xdrData.Give = powerPack.m_fGive;
            xdrData.Pei = powerPack.m_fPei;
            xdrData.PeiPrice = powerPack.m_fPeiPrice;
            xdrData.Profit = powerPack.m_fProfit;
        }

    }
}
